#include "datablock_info.h"
#include "ui_datablock_info.h"
datablock_info::datablock_info(QWidget *parent)
    : QWidget(parent), ui(new Ui::datablock_info)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_StyledBackground); // 这句不加,样式表是加载不出来的
}

bool datablock_info::setBlockInfo(const DataBlock &data)
{
    const QString oldPath = m_data.icon_path;
    m_currentId = data.id;
    m_data = data;

    // 重置控件尺寸
    this->setMinimumSize(0, 0);
    this->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
    // 设置图标
    if (oldPath != data.icon_path)
    {
        QPixmap pix;
        if (QFile::exists(data.icon_path))
        {
            pix.load(data.icon_path);
            pix = pix.scaled(
                ui->label_icon->size(),  // 目标尺寸
                Qt::KeepAspectRatio,     // 保留宽高比
                Qt::SmoothTransformation // 平滑缩放
            );
        }
        ui->label_icon->setPixmap(pix);
    }
    // 处理数据显示，保留一位小数
    QString displayData = data.data;
    if (data.data != "--")
    {
        bool ok;
        double num = data.data.toDouble(&ok);
        if (ok)
        {
            // 保留一位小数显示
            displayData = QString::number(num, 'f', 1);
        }
    }
    // 设置文本
    ui->label_data->setText(displayData + data.unit);

    int newStatus;
    if (data.data == "--")
    {
        ui->label_status->setText("离线");
        newStatus = 1;
    }
    else
    {
        double num = data.data.toDouble();
        if (num < m_criticalThreshold)
        {
            ui->label_status->setText("在线");
            newStatus = 2;
        }
        else
        {
            ui->label_status->setText("警告");
            newStatus = 3;
        }
    }

    // 状态切换，更改样式
    if (newStatus != m_status)
    {
        m_status = newStatus;

        // 强制更新样式
        style()->unpolish(this);
        style()->polish(this);
        update();
        // qDebug() << "状态切换" << m_status;
        emit statusChanged(m_status);
    }
    ui->label_position->setText(data.position);
    return true;
}
